<?php

namespace app\index\controller;

use AlibabaCloud\SDK\Dingtalk\Vyida_1_0\Models\GetRunningTasksResponseBody\result;
use app\admin\common\Constants;
use app\admin\model\WechatMessage;
use think\Controller;
use think\Db;
use think\Loader;
use think\Queue;
use think\Request;
use think\Validate;

class Dingding extends Controller
{
    private $accessKey = 'suited6ds69hhelu4qzua';                                             // 第三方应用的Suitekey
    private $suiteSecret = 'WcWbCLMkdc1dn8_T01Kgm018d2jTiY6eqBQjrk1Jj_5QV8MRMqyCjY04jUCSUQXb';// 第三方应用秘钥

    private $token = 'qev1wPGBos4jOkXSHnyPjHYdZvw1BtqAFAsJV3IiTtWiR';                                       // 钉钉开放平台上，开发者设置的token
    private $encodingAesKey = 'cxlc7FtKC5QuoeOwnn5NPR2tGxe5pCTwzfrPOrF3TJW';                                // 钉钉开放台上，开发者设置的EncodingAESKey
    private $corpid = 'ding3475868534700ebef5bf40eda33b7ba0';                                               // 小程序使用dd.corpId获取这个值

    /**
     * suited6ds69hhelu4qzua
     * WcWbCLMkdc1dn8_T01Kgm018d2jTiY6eqBQjrk1Jj_5QV8MRMqyCjY04jUCSUQXb
     * ding3475868534700ebef5bf40eda33b7ba0
     * B7V1Zi9fvVfg9zPjIoHzSFw54OKTusuogTuumnmOropxbxUPd25Ojd9fkTwY4jHBFLcplmzGUjFI9Xaq1PRhhD
     * */

    /**
     * 钉钉回调请求地址
     * */
    public function notice()
    {
        $input = Request()->param();

        $msg_signature = $input['msg_signature'];
        $timestamp = $input['timestamp'];
        $nonce = $input['nonce'];
        $encrypt = $input['encrypt'];

        Loader::import('dingtalk\DingCallbackCrypto', EXTEND_PATH);
        $crypt = new \DingCallbackCrypto($this->token, $this->encodingAesKey, $this->accessKey);
        $text = $crypt->getDecryptMsg($msg_signature, $timestamp, $nonce, $encrypt);

        $text_arr = json_decode($text, true);
        $biz_type = $text_arr['bizData'][0]['biz_type'];
        if ($biz_type == 2) {
            file_put_contents(RUNTIME_PATH . 'dingding_text.txt', $text);
        } else if ($biz_type == 4) {
            file_put_contents(RUNTIME_PATH . 'dingding_drop_text.txt', $text);
        }

        return $crypt->getEncryptedMap("success");
    }

    /**
     * 钉钉获取userid
     * */
    public function ddLogin()
    {
        $input = Request()->param();

        $code = $input['code'];
        $corpid = $input['corpid'];

        if (empty($code)) apiReturn(2, '免登授权码缺失');

        $url = 'https://oapi.dingtalk.com/topapi/v2/user/getuserinfo';

        $access_token = $this->getAccessToken();

        $url = $url . '?access_token=' . $access_token;
        $data = [
            'code' => $code
        ];

        $header[] = 'content-type: application/json';
        $json = httpsRequest($url, json_encode($data), $header);
        $result = json_decode($json, true);

        file_put_contents(RUNTIME_PATH . 'login_error.txt', "code = $code , access_token = $access_token , corpid = $corpid" . PHP_EOL . $json, FILE_APPEND);

        if ($result['errcode'] == 0) {
            $info = [
                'userid' => $result['result']['userid'],
                'unionid' => $result['result']['unionid']
            ];

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '获取用户信息失败');
        }
    }


    /**
     * 获取SuiteTicket
     * */
    public function getSuiteTicket()
    {
        $dd_notice = file_get_contents(RUNTIME_PATH . 'dingding_text.txt');
        $dd_notice = json_decode($dd_notice, true);

        $biz_data = json_decode($dd_notice['bizData'][0]['biz_data'], true);
        $suiteTicket = $biz_data['suiteTicket'];

        return $suiteTicket ? : '';
    }

    /**
     * 获取签名
     * */
    public function getSign($millisecond)
    {
        $suiteTicket = $this->getSuiteTicket();                                           // 钉钉给应用推送的ticket，测试应用随意填写如：TestSuiteTicket，正式应用需要从推送回调获取suiteTicket。
        $suiteSecret = $this->suiteSecret;                                                // 三方应用秘钥
        $signStr = $millisecond . "\n" . $suiteTicket;
        $hmac_sha256_str = base64_encode(hash_hmac("sha256", $signStr, $suiteSecret, true));

        $signature = urlencode($hmac_sha256_str);

        return $signature;
    }


    /**
     * 服务商获取第三方应用授权企业的access_token
     * 文档地址：https://open.dingtalk.com/document/isvapp-server/obtains-the-enterprise-authorized-credential
     * */
    public function getAccessToken()
    {
        $json = file_get_contents(RUNTIME_PATH . 'dd_access_token.json');
        $result = json_decode($json, true);

        if (!$result || !$result['access_token'] || $result['expires_time'] <= time()) {
            $url = 'https://oapi.dingtalk.com/service/get_corp_token';
            $accessKey = $this->accessKey;
            $timestamp = getMillisecond();
            $suiteTicket = $this->getSuiteTicket();
            $signature = $this->getSign($timestamp);
            $auth_corpid = $this->corpid;

            $data = [
                'accessKey' => $accessKey,
                'timestamp' => $timestamp,
                'suiteTicket' => $suiteTicket,
                'signature' => $signature,
                'auth_corpid' => $auth_corpid
            ];

            $url = $url . '?accessKey=' . $accessKey . '&timestamp=' . $timestamp . '&suiteTicket=' . $suiteTicket . '&signature=' . $signature . '&auth_corpid=' . $auth_corpid;

            $header[] = 'content-type: application/json';
            $json = httpsRequest($url, json_encode($data), $header);
            $result = json_decode($json, true);

            if ($result['errcode'] == 0) {
                $result['expires_time'] = time() + $result['expires_in'] - 60;

                file_put_contents(RUNTIME_PATH . 'dd_access_token.json', json_encode($result));
            } else {
                return false;
            }
        }

        return $result['access_token'];
    }

    public function getAuthCorpId()
    {
        $json = file_get_contents(RUNTIME_PATH . 'dingding_drop_text.txt');

        return json_decode($json, true)['bizData'][0]['corp_id'];
    }

    /**
     * 获取第三方应用授权企业的accessToken
     * 文档地址：https://open.dingtalk.com/document/isvapp-server/obtain-the-access_token-of-the-authorized-enterprise
     * */
    public function getDropAccessToken()
    {
        $json = file_get_contents(RUNTIME_PATH . 'dd_drop_access_token.json');
        $result = json_decode($json, true);

        if (!$result || !$result['access_token'] || $result['expires_time'] <= time()) {
            $url = 'https://api.dingtalk.com/v1.0/oauth2/corpAccessToken';
            $accessKey = $this->accessKey;
            $suiteSecret = $this->suiteSecret;
            $auth_cropid = $this->getAuthCorpId();
            $suiteTicket = $this->getSuiteTicket();

            $data = [
                'suiteKey' => $accessKey,
                'suiteSecret' => $suiteSecret,
                'authCorpId' => $auth_cropid,
                'suiteTicket' => $suiteTicket
            ];

            $header[] = 'content-type: application/json';
            $json = httpsRequest($url, json_encode($data), $header);
            $result = json_decode($json, true);
            if ($result['errcode'] == 0) {
                $result['expires_time'] = time() + $result['expires_in'] - 60;

                file_put_contents(RUNTIME_PATH . 'dd_drop_access_token.json', json_encode($result));
            } else {
                return false;
            }
        }
        return $result['access_token'];
    }

    /**
     * 获取agent_id
     * */
    public function getAgentId()
    {
        $url = 'https://oapi.dingtalk.com/service/get_auth_info';

        $accessKey = $this->accessKey;
        $timestamp = getMillisecond();
        $suiteTicket = $this->getSuiteTicket();
        $signature = $this->getSign($timestamp);

        $suite_key = $this->accessKey;
        $auth_corpid = $this->corpid;

        $url = $url . '?accessKey=' . $accessKey . '&timestamp=' . $timestamp . '&suiteTicket=' . $suiteTicket . '&signature=' . $signature;
        $data = [
            'suite_key' => $suite_key,
            'auth_corpid' => $auth_corpid
        ];

        $header[] = 'content-type: application/json';
        $json = httpsRequest($url, json_encode($data), $header);
        $result = json_decode($json, true);

        return $result['auth_info']['agent'][0]['agentid'];
    }

    /**
     * 获取spaceId
     * */
    public function getSpaceId()
    {
        $access_token = $this->getAccessToken();
        if ($access_token === false) apiReturn(2, '获取access_token失败');

        $domain = 'aaa';
        $agent_id = $this->getAgentId();

        $url = 'https://oapi.dingtalk.com/cspace/get_custom_space?access_token=' . $access_token . '&domain=' . $domain . '&agent_id=' . $agent_id;
        $info = file_get_contents($url);
        $info = json_decode($info, true);

        if ($info['errcode'] == 0) {
            apiReturn(1, '获取数据成功', $info['spaceid']);
        } else {
            apiReturn(2, $info['errmsg']);
        }
    }

    /**
     * 给某用户授权spaceid
     * */
    public function authorityToUser()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '用户ID缺失');

        $dd_userid = Db::name('user')->where(['id' => $user_id])->value('dd_userid');
        if (empty($dd_userid)) apiReturn(2, '请前往【我的】绑定钉钉');

        $url = 'https://oapi.dingtalk.com/cspace/grant_custom_space?';

        $param = [
            'access_token' => $this->getAccessToken(),
            'agent_id' => $this->getAgentId(),
            'domain' => 'aaa',
            'type' => 'add',
            'userid' => $dd_userid,
            'path' => '/'
        ];

        $url = $url . http_build_query($param);
        $res = file_get_contents($url);
        if ($res) {
            apiReturn(1, '成功');
        } else {
            apiReturn(2, '权限不足');
        }
    }

    /**
     * 预览授权
     * */
    public function previewAuth($user_id, $unionId)
    {
        $url = "https://api.dingtalk.com/v1.0/drive/spaces/{$this->getSpaceId()}/files/customSpacePrivileges?x-acs-dingtalk-access-token=" . $this->getAccessToken();

        $header[] = 'Content-Type:application/json';

        $data = [
            'type' => 'preview',
            'userId' => $user_id,
            'fileIds' => [0],
            'duration' => 3000,
            'unionId' => $unionId
        ];

        $res = httpsRequest($url, json_encode($data), $header);
        echo "<pre>";
        print_r($res);
        exit;
    }


    //更新dd_userid && dd_unionid
    public function saveDdUserInfo()
    {
        $input = Request()->param();

        $uid = $input['uid'];
        $userid = $input['userid'];
        $unionid = $input['unionid'];

        if (empty($uid)) apiReturn(2, '用户ID不能为空');
        if (empty($userid)) apiReturn(2, 'userid不能为空');

        $res = Db('user')->where(['id' => $uid])->update(['dd_unionid' => $unionid, 'dd_userid' => $userid]);

        if ($res) {
            apiReturn(1, '成功');
        } else {
            apiReturn(2, '失败');
        }
    }

    //解绑钉钉
    public function unbind()
    {
        $input = Request()->param();

        $uid = $input['uid'];

        if (empty($uid)) apiReturn(2, '会员ID不能为空');

        $res = Db('user')->where(['id' => $uid])->update(['dd_userid' => '', 'dd_unionid' => '']);
        if ($res) {
            apiReturn(1, '成功');
        } else {
            apiReturn(2, '失败');
        }
    }

    //提交申请
    public function submit_application()
    {
        $input = Request()->param();

        $uid = $input['uid'];                   //用户ID也就是申请人ID
        $lng = $input['lng'];
        $lat = $input['lat'];
        $seal_id = $input['seal_id'];                    // 印章ID
        $app_id = $input['app_id'];                      // 审批类型ID
        $name = $input['name'];                          // 文件名称
        $file_number = $input['file_number'];            // 文件编号
        $company_id = $input['company_id'];
        $imgs = $input['imgs'];                            // 图片
        $remark = $input['remark'];                        // 备注
        $dd_file = $input['dd_file'];                      // 申请文档 我觉得上传到本地了，是个地址
        $check_approver_ids = $input['check_approver_ids'];// 审批人id集合
        $check_carbon_ids = $input['check_carbon_ids'];    // 抄送人id集合
        $content = $input['content'];                      // 申请内容
        $is_pc = $input['is_pc'] ? : false;

        if (empty($uid)) apiReturn(2, '申请人ID为空或者格式错误');
        if (empty($lng) || empty($lat)) apiReturn(2, '缺少定位信息');
        if (empty($seal_id)) apiReturn(2, '请选择申请项目');
        if (empty($app_id)) apiReturn(2, '请选择审批类型');
        if (empty($check_carbon_ids)) apiReturn(2, '请添加抄送人');
        if (empty($file_number)) apiReturn(2, '请输入文件编号');
        if (empty($name)) apiReturn(2, '文件名称不能为空');
        if (empty($content)) apiReturn(2, '请输入申请内容');

        $is_free = Db('approval')->where(['id' => $app_id])->value('is_free');
        if ($is_free == 2 && empty($check_approver_ids)) apiReturn(2, '请添加审批人');

        $time = time();

        $check_approver_ids = explode(',', $check_approver_ids);
        $check_carbon_ids = explode(',', $check_carbon_ids);

        Db::startTrans();
        try {
            $data = [
                'uid' => $uid,                  //用户ID也就是申请人ID
                'lng' => $lng,
                'lat' => $lat,
                'seal_id' => $seal_id,          //印章ID
                'app_id' => $app_id,            //审批类型ID
                'name' => $name,                //文件名称
                'file_number' => $file_number,  //文件编号
                'company_id' => $company_id,
                'imgs' => $imgs,                //图片
                'remark' => $remark,            //备注
                'dd_file' => $dd_file,          //申请文档 我觉得上传到本地了，是个地址
                'content' => $content,
                'create_time' => $time
            ];
            // 新增申请记录
            $form_id = Db('app_form')->insertGetId($data);

            $approval_process_data = [];
            if ($is_free == 2) {
                // 自由审批流程
                foreach ($check_approver_ids as $k => $v) {
                    $approval_process_data[] = [
                        'uid' => $v,
                        'form_id' => $form_id,
                        'company_id' => $company_id,
                        'status' => $k == 0 ? 1 : 4,
                        'create_time' => $time
                    ];

                    if ($k == 0) {
                        file_put_contents(RUNTIME_PATH . 'send_log.txt', "申请自由审批流程 ---- 给审批人发送【用章申请提醒】消息" . PHP_EOL, FILE_APPEND);

                        // 发送模板消息（用章申请提醒）
                        $dd_userid = Db('user')->where(['id' => $v])->value('dd_userid');
                        $this->sendApprovalSmg($dd_userid, $uid, $form_id, $name);
                    }
                }
            } else {
                $app_list = Db('approver')->where(['app_id' => $app_id])->order('sort asc')->select();

                foreach ($app_list as $k => $v) {
                    $approval_process_data[] = [
                        'uid' => $v['uid'],
                        'form_id' => $form_id,
                        'company_id' => $company_id,
                        'status' => $k == 0 ? 1 : 4,
                        'create_time' => $time
                    ];

                    if ($k == 0) {
                        file_put_contents(RUNTIME_PATH . 'send_log.txt', "申请非自由审批流程 ---- 给审批人发送【用章申请提醒】消息" . PHP_EOL, FILE_APPEND);
                        // 发送模板消息（用章申请提醒）
                        $dd_userid = Db('user')->where(['id' => $v['uid']])->value('dd_userid');
                        $this->sendApprovalSmg($dd_userid, $uid, $form_id, $name);
                    }
                }
            }
            // 新增审批流程
            Db('approval_process')->insertAll($approval_process_data);

            // 新增抄送人权限
            $carbon_auth_data = [];
            foreach ($check_carbon_ids as $v) {
                $carbon_auth_data[] = [
                    'form_id' => $form_id,
                    'carbon_uid' => $v,
                    'create_time' => $time
                ];
            }
            Db::name('carbon_auth')->insertAll($carbon_auth_data);

            Db::commit();
            if ($is_pc) {
                return [
                    'code' => 1,
                    'msg' => '成功',
                    'url' => url('/admin/app_form/index')
                ];
            } else {
                apiReturn(1, '成功', $form_id);
            }
        } catch (\Exception $e) {
            Db::rollback();
            if ($is_pc) {
                return [
                    'code' => 2,
                    'msg' => '失败',
                ];
            } else {
                apiReturn(2, '失败');
            }
        }
    }

    /**
     * 给审核人发送【用章申请提醒】
     * @param int    $dd_userid 钉钉userid
     * @param int    $uid       申请人ID
     * @param int    $form_id   申请记录id
     * @param string $name      文件名称
     * */
    public function sendApprovalSmg($dd_userid, $uid, $form_id, $name)
    {
        if ($dd_userid) {
            // 申请人
            $apply_username = Db('user')->where(['id' => $uid])->value('username');
            // 申请部门
            $department_id = Db('staff')->where(['uid' => $uid])->value('department_id');
            $list = explode(',', $department_id);
            $d_id = $list[0];
            $partment_name = Db('department')->where(['id' => $d_id])->value('name');

            // 申请项目
            $seal_id = Db::name('app_form')->where(['id' => $form_id])->value('seal_id');
            $seal_name = Db::name('seal')->where(['id' => $seal_id])->value('name');

            $date = date('Y-m-d H:i:s');

            $data = [
                'apply_user' => $apply_username,
                'apply_department' => $partment_name,
                'time' => $date,
                'seal_name' => $seal_name,
                'text_name' => $name,
            ];
            sendDDMsg($this->getAccessToken(), $this->getAgentId(), 'f3465a4251b24cbeb23f15d84690f3ef', $dd_userid, json_encode($data, JSON_UNESCAPED_UNICODE));
        }
    }

    public function to_examine()
    {
        $input = Request()->param();

        $form_id = $input['form_id'];//申请表单ID
        $uid = $input['uid'];        //审批人ID
        $state = $input['state'];    //state 1:同意 2：拒绝
        $remark = $input['remark'];
        $remark_content = $input['remark_content'];

        if (!$form_id) apiReturn(2, '表单ID为空');
        if (!$uid) apiReturn(2, '审批人ID为空');
        if (!$state) apiReturn(2, '操作类型为空');

        $form_info = Db('app_form')->where(['id' => $form_id])->find();

        //可能提交了几次，找到最大的那条记录ID
        $mid = Db('approval_process')->where(['form_id' => $form_id, 'uid' => $uid])->order('id desc')->value('id');
        if ($state == 1) {
            // 同意

            //同意 同意的话还要看后面的有没有人，审批流程有没有结束
            Db('approval_process')->where(['id' => $mid])->update(['status' => 2, 'app_time' => time()]);

            $id_list = Db('approval_process')->where(['form_id' => $form_id])->order('id asc')->field('id')->select();
            $max_ids = max($id_list);
            $max_id = $max_ids['id'];
            $ids = array_column($id_list, 'id');
            //当前ID的下标值
            $key = array_search($mid, $ids);
            //看最大值大于$id不，大于就代表后面还有审批人
            if ($max_id > $mid) {
                // 流程审核未完成

                $next_id = $id_list[$key + 1]['id'];
                //轮到下一个人审核 status:1为当前审核人
                Db('approval_process')->where(['id' => $next_id])->update(['status' => 1]);

                file_put_contents(RUNTIME_PATH . 'send_log.txt', "整个流程审核未完成 ---- 给下一个审核人发【用章申请提醒】" . PHP_EOL, FILE_APPEND);
                // 给下一个审核人发送模板消息（用章申请提醒）

                $sh_uid = Db('approval_process')->where(['id' => $next_id])->value('uid');// 下一个审核人用户id
                $dd_userid = Db('user')->where(['id' => $sh_uid])->value('dd_userid');
                $this->sendApprovalSmg($dd_userid, $form_info['uid'], $form_id, $form_info['name']);
            } else {
                //审批流程走完
                Db('approval_process')->where(['form_id' => $form_id])->update(['form_state' => 1]);
                Db('app_form')->where(['id' => $form_id])->update(['status' => 4]);

                file_put_contents(RUNTIME_PATH . 'send_log.txt', "整个流程审核完成 ---- 给申请人发【用章申请完成提醒】" . PHP_EOL, FILE_APPEND);
                //给申请人发【用章申请完成提醒】
                $dd_userid = Db('user')->where(['id' => $form_info['uid']])->value('dd_userid');
                if ($dd_userid) {
                    // 申请项目
                    $seal_id = Db('app_form')->where(['id' => $form_id])->value('seal_id');
                    $seal_type = Db('seal')->where(['id' => $seal_id])->value('seal_type');
                    $configModel = new \app\admin\model\Config();
                    $res = $configModel->getConfigCacheByName(Constants::$SEAL_TYPE_KEY);
                    $type_list = array_merge($res);
                    if ($seal_type == 1) {
                        $type_name = $type_list[0]['name'];
                    } elseif ($seal_type == 2) {
                        $type_name = $type_list[1]['name'];
                    } elseif ($seal_type == 3) {
                        $type_name = $type_list[2]['name'];
                    } elseif ($seal_type == 4) {
                        $type_name = $type_list[3]['name'];
                    }
                    // 申请人
                    $username = Db('user')->where(['id' => $uid])->value('username');

                    $date = date('Y-m-d H:i:s', $form_info['create_time']);

                    $data = [
                        'item' => $type_name,
                        'user' => $username,
                        'time' => $date,
                        'result' => '通过'
                    ];
                    // 用章申请完成提醒
                    sendDDMsg($this->getAccessToken(), $this->getAgentId(), '9651b2793802473cb301e490b629a69f', $dd_userid, json_encode($data, JSON_UNESCAPED_UNICODE));
                }
            }

            // 给抄送人发送【用章申请审核结果提醒】
            $dd_userid_list = Db::name('carbon_auth c')->join('tp_user u', 'c.carbon_uid = u.id')
                ->field('u.dd_userid')
                ->where(['c.form_id' => $form_id, 'c.is_auth' => 1])
                ->select();
            // 给抄送人送用章申请审核结果
            if ($dd_userid_list) {
                $dd_userid_arr = array_filter(array_column($dd_userid_list, 'dd_userid'));
                if($dd_userid_arr){
                    foreach($dd_userid_arr as $v){
                        file_put_contents(RUNTIME_PATH . 'send_log.txt', "审核通过 ---- 给抄送人发【用章申请审核结果】-----$v" . PHP_EOL, FILE_APPEND);
                        $this->sendExamineMsg($v, $form_info['uid'], $form_id, $form_info['name'], 1, date('Y-m-d H:i:s', $form_info['create_time']));
                    }
                }
            }

        } elseif ($state == 2) {
            //要写拒绝原因
            if (!$remark_content) {
                $remark_content = '';
            } else {
                $remark = 4;
            }
            Db('app_form')->where(['id' => $form_id])->update(['status' => 3]);
            Db('approval_process')->where(['id' => $mid])->update(['status' => 3, 'remark' => $remark, 'remark_content' => $remark_content, 'app_time' => time()]);

            file_put_contents(RUNTIME_PATH . 'send_log.txt', "审核失败 ---- 给申请人发【用章申请审核结果】" . PHP_EOL, FILE_APPEND);
            // 给申请人发【用章申请审核结果】
            $dd_userid = Db('user')->where(['id' => $form_info['uid']])->value('dd_userid');
            $this->sendExamineMsg($dd_userid, $form_info['uid'], $form_id, $form_info['name'], 2, date('Y-m-d H:i:s', $form_info['create_time']));

        }

        apiReturn(1, '成功');
    }

    /**
     * 给抄送人或申请人发送【用章申请审核结果提醒】
     * @param string $dd_userid   钉钉userid
     * @param int    $uid         申请人ID
     * @param int    $form_id     申请记录id
     * @param string $name        文件名称
     * @param int    $state       审核状态
     * @param int    $create_time 申请时间
     * */
    public function sendExamineMsg($dd_userid, $uid, $form_id, $name, $state, $create_time)
    {
        if ($dd_userid) {
            // 申请人
            $apply_username = Db('user')->where(['id' => $uid])->value('username');

            // 申请项目
            $seal_id = Db::name('app_form')->where(['id' => $form_id])->value('seal_id');
            $seal_name = Db::name('seal')->where(['id' => $seal_id])->value('name');

            $date = date('Y-m-d H:i:s');

            $data = [
                'apply_user' => $apply_username,
                'apply_time' => $create_time,
                'seal_name' => $seal_name,
                'file_text' => $name,
                'examine_result' => $state == 1 ? '通过' : '拒绝',
                'examine_time' => $date,
                'id_value' => $form_id
            ];

            // 用章申请审核结果提醒
            sendDDMsg($this->getAccessToken(), $this->getAgentId(), '73d8e345d71a47bd9fbc8a0e30e70e9e', $dd_userid, json_encode($data, JSON_UNESCAPED_UNICODE));
        }
    }


    public function useSealImg()
    {
        $input = Request()->param();

        $id = $input['id'];
        $imgs = $input['imgs'];
        $dd_used_file = $input['dd_used_file'];

        if (!$id) apiReturn(2, '表单ID为空');
        //        if (!$imgs) apiReturn(2, '图片不能为空');

        $res = Db('app_form')->where(['id' => $id])->update(['used_img' => $imgs, 'dd_used_file' => $dd_used_file, 'update_time' => time()]);
        if ($res) {
            //上传图片完成，就要改变表单状态
            Db('approval_process')->where(['form_id' => $id])->update(['form_state' => 2]);

            $params['form_id'] = $id;
            $time = 60 * 60 * 24;
            $params['status'] = 1;//1是上传图片 24小时之后变状态   2：是判断24小时之后有没有上传图片去锁定用户
            Queue::later($time, Constants::$DELAY_QUEUE['handler'], $params, Constants::$DELAY_QUEUE['queue']);

            apiReturn(1, '成功');
        } else {
            apiReturn(2, '失败');
        }
    }

    // 审批人列表
    public function selectApprover()
    {
        $input = Request()->param();

        $company_id = $input['company_id'];
        $search_value = $input['search_value'];

        if (!$company_id) apiReturn(2, '公司ID为空');

        $condition['a.company_id'] = $company_id;
        if ($search_value) $condition['b.username|b.account'] = ['like', "%$search_value%"];

        $condition['c.is_approver'] = 2;//是审批人才可以

        $list = Db::name('staff a')
            ->join('tp_user b', 'a.uid=b.id', 'LEFT')
            ->join('tp_position c', 'a.position_id=c.id', 'LEFT')
            ->field('a.id,a.uid,a.department_id,b.username,b.mobile')
            ->group('uid')
            ->where($condition)
            ->select();
        if ($list) {
            foreach ($list as &$v) {
                $department_list = [];
                if ($department_id = $v['department_id']) {
                    $department_list = Db::name('department')->field('name')->where(['id' => ['IN', $department_id]])->select();
                }
                $v['department_list'] = $department_list ? implode(',', array_column($department_list, 'name')) : '';
                $v['is_disabled'] = false;
            }
            apiReturn(1, '成功', $list);
        } else {
            apiReturn(2, '暂无数据', []);
        }
    }

    // 抄送人列表
    public function selectCarbon()
    {
        $input = Request()->param();

        $company_id = $input['company_id'];
        $search_value = $input['search_value'];

        if (!$company_id) apiReturn(2, '公司ID为空');

        $condition['a.company_id'] = $company_id;
        if ($search_value) $condition['b.username|b.account'] = ['like', "%$search_value%"];

        $condition['a.is_carbon'] = 2;

        $list = Db::name('staff a')
            ->join('tp_user b', 'a.uid=b.id', 'LEFT')
            ->join('tp_position c', 'a.position_id=c.id', 'LEFT')
            ->field('a.id,a.uid,a.department_id,b.username,b.mobile')
            ->group('uid')
            ->where($condition)
            ->select();

        if ($list) {
            foreach ($list as &$v) {
                $department_list = [];
                if ($department_id = $v['department_id']) {
                    $department_list = Db::name('department')->field('name')->where(['id' => ['IN', $department_id]])->select();
                }
                $v['department_list'] = $department_list ? implode(',', array_column($department_list, 'name')) : '';
                $v['sort'] = 0;
            }
            apiReturn(1, '成功', $list);
        } else {
            apiReturn(2, '暂无数据', []);
        }
    }

    /**
     * 抄送人权限转移-用户列表
     * */
    public function carbonAuthMoveUserList()
    {
        $input = Request()->param();

        $id = $input['id'];                // app_form表主键id
        $company_id = $input['company_id'];// 公司id
        $search_value = $input['search_value'];

        if (empty($id)) apiReturn(2, 'ID缺失');
        if (!$company_id) apiReturn(2, '公司ID为空');

        $auth_uid_list = Db::name('carbon_auth')->field('carbon_uid,get_uid')->where(['form_id' => $id, 'is_auth' => 1])->select();
        $carbon_uid_arr = array_column($auth_uid_list, 'carbon_uid');
        $get_uid_arr = array_column($auth_uid_list, 'get_uid');
        // 查询用户列表是需要排除的用户id
        $move_user_ids = array_diff(array_unique(array_merge($carbon_uid_arr, $get_uid_arr)), [0]);
        $move_user_ids[] = 1;

        $condition['a.uid'] = ['NOT IN', implode(',', $move_user_ids)];

        $condition['a.company_id'] = $company_id;
        if ($search_value) $condition['b.username|b.account'] = ['like', "%$search_value%"];

        $list = Db::name('staff a')
            ->join('tp_user b', 'a.uid=b.id', 'LEFT')
            ->join('tp_position c', 'a.position_id=c.id', 'LEFT')
            ->field('a.id,a.uid,a.department_id,b.username,b.mobile')
            ->group('uid')
            ->where($condition)
            ->select();

        if ($list) {
            foreach ($list as &$v) {
                $department_list = [];
                if ($department_id = $v['department_id']) {
                    $department_list = Db::name('department')->field('name')->where(['id' => ['IN', $department_id]])->select();
                }
                $v['department_list'] = $department_list ? implode(',', array_column($department_list, 'name')) : '';
                $v['sort'] = 0;
            }
            apiReturn(1, '成功', $list);
        } else {
            apiReturn(2, '暂无数据', []);
        }
    }

    /**
     * 抄送人权限转移
     * */
    public function moveCarbonAuth()
    {
        $input = Request()->param();

        $id = $input['id'];// form_id
        $uid = $input['uid'];
        $get_uid = $input['get_uid'];

        if (empty($id)) apiReturn(2, 'ID缺失');
        if (empty($uid)) apiReturn(2, '转移人用户ID缺失');
        if (empty($get_uid)) apiReturn(2, '权限转移目标用户ID缺失');

        $auth_id = Db::name('carbon_auth')->where(['form_id' => $id, 'carbon_uid' => $uid, 'get_uid' => $get_uid])->value('id');

        $data = [
            'form_id' => $id,
            'carbon_uid' => $uid,
            'get_uid' => $get_uid,
            'is_move' => 1,
            'is_auth' => 1
        ];
        if ($auth_id) {
            $data['update_time'] = time();
            $res = Db::name('carbon_auth')->where(['id' => $auth_id])->update($data);
        } else {
            $data['create_time'] = time();
            $res = Db::name('carbon_auth')->insert($data);
        }

        if ($res) {
            apiReturn(1, '转移权限成功');
        } else {
            apiReturn(2, '转移权限失败');
        }
    }

    //部门管理
    public function department_management()
    {
        $input = Request()->param();

        $company_id = $input['company_id'];
        $pid = $input['pid'] ? : 0;
        $name = $input['name'];

        if (!$company_id) apiReturn(2, '公司ID为空');

        //一级部门列表
        $sub_list = Db::name('department')->where(['pid' => 0, 'company_id' => $company_id, 'is_del' => 0])->order('id desc')->select();

        //现在PID是下标，小程序是传的下标过来的
        if ($pid > -1) $where['id'] = $sub_list[$pid]['id'];
        if ($name) $where['name'] = ['like', '%' . $name . '%'];

        $where['company_id'] = $company_id;
        $where['is_del'] = ['eq', 0];
        $list = Db::name('department')->where($where)->select();
        foreach ($list as $k => $v) {
            if ($v['pid'] == 0) {
                //无上级部门
                $list[$k]['superior_name'] = '无';
            } else {
                //上级部门名称
                $list[$k]['superior_name'] = Db::name('department')->where(['id' => $v['pid']])->value('name');
            }
            if ($v['sort'] == 0) {
                $list[$k]['sort'] = 9999;
            }
        }

        foreach ($list as $key => $row) {
            $volume[$key] = $row['sort'];
            $edition[$key] = $row['create_time'];
        }

        array_multisort($volume, SORT_ASC, $edition, SORT_DESC, $list);
        $sub_list ? $data['sub_list'] = $sub_list : [];
        $list ? $data['list'] = $list : [];
        apiReturn(1, '成功', $data);
    }

    /**
     * OCR获取图片文字信息
     * */
    public function getOcrInfo()
    {
        $input = Request()->param();

        $img_url = $input['img_url'];

        if (empty($img_url)) apiReturn(2, '图片地址不能为空');

        $url = "https://api.topthink.com/ocr/txt?";
        $param = [
            'appCode' => '93fa836c339c921493f626c2ee784906',
            'imgurl' => $img_url
        ];

        $url = $url . http_build_query($param);

        $info = json_decode(file_get_contents($url), true);
        if ($info['code'] == 0) {
            apiReturn(1, '图片识别成功', $info['data'][0]['texts']);
        } else {
            apiReturn(2, '图片识别失败');
        }
    }
}
